package com.bear.fastrepair.mvvm.ui.employee.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import androidx.lifecycle.LifecycleOwner
import com.bear.fastrepair.base.BaseDialog
import com.bear.fastrepair.databinding.DialogUpdateAppBinding
import com.bear.fastrepair.entity.AppVersion
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModel
import com.bear.fastrepair.mvvm.ui.employee.fragment.EmployeePersonalFragment
import com.bear.fastrepair.utils.launch
import com.blankj.utilcode.util.*
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException

class AppUpdateProgressDialog(context: Context, private val updateAppInfo: AppVersion, private val viewModel: EmployeeViewModel, private val lifecycleOwner: LifecycleOwner) : BaseDialog(context) {
    private lateinit var binding: DialogUpdateAppBinding
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogUpdateAppBinding.inflate(LayoutInflater.from(context))
        setContentView(binding.root)
        setCancelable(false)
        viewModel.downloadApp(updateAppInfo.downloadUrl)
        viewModel.appResponse.observe(lifecycleOwner) {
            viewModel.launch {
                withContext(Dispatchers.IO) {
                    val path = "${context.externalCacheDir?.absolutePath}/apk/${updateAppInfo.downloadUrl.substringAfterLast("/")}"
                    val file = FileUtils.getFileByPath(path)
                    if (!FileUtils.createOrExistsFile(file)) {
                        ToastUtils.showLong("系统错误，无法下载文件")
                        return@withContext
                    }
                    try {
//                        FileIOUtils.writeFileFromIS(file, it.byteStream(), true) {
//
//                        }
                        val contentLength = it.contentLength()
                        var currentLength = 0L
                        val buffer = ByteArray(1024)
                        var percent = 0
                        file.outputStream().use { fOut ->
                            it.byteStream().use { rIn ->
                                var len = rIn.read(buffer)
                                while (len != -1) {
                                    fOut.write(buffer, 0, len)
                                    currentLength += len
                                    if ((currentLength * 100 / contentLength).toInt() > percent) {
                                        percent = (currentLength * 100 / contentLength).toInt()
                                        withContext(Dispatchers.Main) {
                                            binding.progressCount.text = "正在下载：$percent%"
                                        }
                                    }
                                    len = rIn.read(buffer)
                                }
                                withContext(Dispatchers.Main) {
                                    dismiss()
                                    if (!XXPermissions.isGranted(context, Permission.REQUEST_INSTALL_PACKAGES)) {
                                        XXPermissions.with(context).permission(Permission.REQUEST_INSTALL_PACKAGES).request { _, all ->
                                            if (all) AppUtils.installApp(file)
                                            else ToastUtils.showLong("安装应用权限被拒绝，请打开权限重新尝试更新")
                                        }
                                    } else {
                                        AppUtils.installApp(file)
                                    }
                                }
                            }
                        }
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
                dismiss()
            }
        }
    }
}